<template>
  <el-dialog :title="id?'编辑业务':'新增业务'" v-if="dialogFormVisible" :visible.sync="dialogFormVisible" width="1524px">
    <span style="color:red">{{errorTips}}</span>
    <el-tabs  v-model="activeName" v-loading="loading">
      <el-tab-pane label="业务基本信息" name="basic">
        <basic ref="basic"  :groups="groups" :formList="formList||[]" :formKey="formKey" :basic="json.basic"
          @setFormKeyAndColumns="setFormKeyAndColumns" @setValue="setValue"
          @changeViewType="(e)=>{viewType=e}"
          @changeViewName="(e)=>{viewName=e}"
          @changeViewKey="(e)=>{viewKey=e}"/>
      </el-tab-pane>
      <el-tab-pane label="初始查询条件" name="apiInfo">
        <api-info ref="apiInfo" :formKey="formKey" :extraFormKeys="extraFormKeys" :formColumns="formColumns"
          :apiInfo="json.apiInfo" @setValue="setValue" />
      </el-tab-pane>
      <el-tab-pane label="字段设置" name="column">
        <column ref="column" :formTitiles="formTitiles" :viewType="viewType" :formKey="formKey" :listRole="listRole||[]"
          :extraFormKeys="extraFormKeys" :formColumns="formColumns" :propList="json.list" :searchTypes="searchTypes"
          @setValue="setValue" />
      </el-tab-pane>
      <!-- <el-tab-pane label="搜索功能" name="search">
        <search ref="search" :formColumns="formColumns" :search="json.search" @setValue="setValue"/>
      </el-tab-pane> -->
      <el-tab-pane label="边栏树" name="tree">
        <tree ref="tree" :formList="formList||[]" :formColumns="formColumns" :treeConfig="json.treeConfig"
        @setValue="setValue"
         @changeRefreshByDel="(e)=>{refreshByDel=e}"/>
      </el-tab-pane>
      <el-tab-pane label="业务操作" name="action">
        <action ref="action" :listRole="listRole||[]" :viewKey="viewKey" :refreshByDel="refreshByDel" :viewType="viewType" :viewName="viewName"  :primaryKeyFieldObj="primaryKeyFieldObj" :formKey="formKey" :extraFormKeys="extraFormKeys" :action="json.action" @setValue="setValue" />
      </el-tab-pane>
    </el-tabs>
    <!-- <div style="padding:40px 0 0 700px;"> -->
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false" :loading="loading">取 消</el-button>
      <el-button type="success" @click="getDataFromTabs(true)" :loading="loading">保存并预览</el-button>
      <el-button type="primary" @click="getDataFromTabs(false)" :loading="loading">保 存</el-button>
    </div>
    <el-dialog title="预览" :visible.sync="previewVisible" width="95vw" append-to-body @close="businessId=null">
      <preview v-if="businessId" :businessId="businessId" />
    </el-dialog>
  </el-dialog>
</template>

<script>
  import PopupManager from "element-ui/lib/utils/popup/popup-manager"
  import {
    formList
  } from "@/api/tool/formManage";
  import {
    listRole
  } from "@/api/system/role";
  import {
    saveOrUpdate
  } from "@/api/tool/business";
  import {
    getDicts
  } from "@/api/system/dict/data";
  import basic from "./basic.vue";
  import apiInfo from "./apiInfo.vue";
  import column from "./column.vue";
  import action from "./action.vue";
  import tree from "./tree.vue";
  import preview from "@/views/tool/view/index.vue";
  import {
    nanoid
  } from 'nanoid';
 import store from '@/store'
  PopupManager.zIndex = 1000
  export default {
    name: "myDialog",
    components: {
      basic,
      apiInfo,
      column,
      action,
      tree,
      preview
    },
    props: {
      groups: {
        type: Array,
        default: ()=>[],
      }
    },
    data() {
      return {
        dialogFormVisible: false,
        loading: false,
        activeName: 'basic',
        id: null,
        formList: null,
        listRole:null,
        viewKey: '', //业务key
        viewName: '', //业务名称
        viewType: 1,
        refreshByDel: false,
        formTitiles: {}, //表名
        primaryKeyFieldObj:{},//表的主键
        formKey: undefined, //主表
        extraFormKeys: [], //附加表
        formColumns: {}, //字段
        dataKeys: null, //已经填写好数据的tabs
        errorTips: '',
        isPreview: false,
        json: {},
        previewVisible: false,
        businessId: null,
        searchTypes: [],
        searchTypeObj: {},

        initThis: {
          id: null,
          formKey: undefined,
          viewKey: '', //业务key
          viewName: '', //业务名称
          formTitiles: {},
          extraFormKeys: [],
          activeName: 'basic',
          dataKeys: null,
          errorTips: '',
          isPreview: false,
          json: {},
          previewVisible: false,
          businessId: null,
          viewType: 1,
          refreshByDel: false,
        },
        autoSave:false,
      };
    },
    methods: {
      open(data,autoSave) {
        this.autoSave = autoSave
        this.loading = true
        setTimeout(() => {
          this.loading = false
        }, 2000)
        Object.keys(this.initThis).forEach(key => {
          this[key] = this.initThis[key]
        })
        if (!this.formList) {
          //获取表单列表
          this.getFormList()
        }
        if (!this.listRole) {
          //获取角色列表
          this.getListRole()
        }
        if (!this.searchTypes.length) {
          this.getSearchTypes()
        }
        if (data) {
          this.id = data.id
          this.formKey = data.formKey
          this.json = JSON.parse(data.json)


          this.viewType = this.json.basic.viewType || 1
          this.viewKey = this.json.basic.viewKey || ''
          this.viewName = this.json.basic.viewName || ''
          this.refreshByDel = this.json.treeConfig.refreshByDel || false

        }
        this.dialogFormVisible = true

        if(autoSave){
          setTimeout(()=>{
            this.getDataFromTabs(false)
          },2500)
        }
      },
      //获取表单列表
      getFormList() {
        formList().then(res => {
          if (res.code == 200) {
            this.formList = res.data.map(item => {
              item.name = `${item.formTitle}(${item.formKey})`
              this.formTitiles[item.formKey] = item.name
              return item
            });
          }
        })
      },
      //获取角色列表
      getListRole() {
        listRole({pageNum:1,pageSize:999}).then(res => {
          if (res.code == 200) {
            this.listRole = res.rows
          }
        })
      },
      //设置key和字段列表
      setFormKeyAndColumns(obj) {
        this.formKey = obj.formKey
        this.extraFormKeys = obj.extraFormKeys
        this.formColumns = obj.formColumns
        this.primaryKeyFieldObj = obj.primaryKeyFieldObj
      },
      //搜索类型
      getSearchTypes() {
        getDicts('sys_comparator_key').then(res => {
          if (res.code == 200) {
            this.searchTypes = res.data
            res.data.forEach(item => {
              this.searchTypeObj[item.dictValue] = item.remark || item.dictLabel
            })
          }
        })
      },
      //获取tabs的数据
      getDataFromTabs(isPreview,count) {
        this.loading = true
        this.businessId = null
        this.isPreview = isPreview
        this.dataKeys = {}
        this.errorTips = ''
        this.$nextTick(() => {
          try{
            this.$refs.basic.submit()
            this.$refs.apiInfo.submit()
            this.$refs.column.submit()
            this.$refs.action.submit()
            this.$refs.tree.submit()
            setTimeout(() => {
              if (Object.keys(this.dataKeys).length < 5) {
                this.loading = false
                let errorTips = '请完善：'
                if (!this.dataKeys.basic) {
                  errorTips += '业务基本信息，'
                }
                if (!this.dataKeys.list) {
                  errorTips += '列表展示字段，'
                }
                if (!this.dataKeys.action) {
                  errorTips += '业务操作，'
                }
                if (!this.dataKeys.treeConfig) {
                  errorTips += '边栏树，'
                }
                this.errorTips = errorTips.substring(0, errorTips.length - 1)
              }
            }, 1000)
          }catch(e){
            if(this.autoSave&&!count||count<4){
              setTimeout(() => {
                this.getDataFromTabs(isPreview,(count||0)+1)
              }, 1500)
            }else{
              this.loading = false
            }
          }
        })
      },
      setValue(data) {
        this.dataKeys[data.tabType] = data.formData
        if (Object.keys(this.dataKeys).length == 5) {
          const {basic,list,action,treeConfig}=this.dataKeys
          this.formKey = basic.formKey
          //字段权限
          const columnAuths = list.map(item => {
            return {
              columnName: item.columnName.substring(item.columnName.indexOf('__') + 2, item.columnName.length),
              authFlag: item.authFlag,
              formKey: item.formKey,
            }
          })

          if (basic.viewType == '1') {
            this.setListSchema(columnAuths)
          } else {
            this.setFormSchema(columnAuths)
          }
        }
      },

      setListSchema(columnAuths) {

        const {basic,list,action,treeConfig}=this.dataKeys,
              primaryKey=basic.formKey+'__'+this.primaryKeyFieldObj[basic.formKey];

        let schema = {
          "type": "page",
          "name": "page__"+basic.viewKey,
          "data":{
          },
          "style": {
            "boxShadow": " 0px 0px 0px 0px transparent"
          },
          "pullRefresh": {
            "disabled": true
          },
          "regions": [
            "body"
          ],
          "body": [{
            "type": "crud",
            "name": "crud__"+basic.viewKey,
            "debug": true,
            "autoGenerateFilter": true,
            "syncLocation": false,
            "api": {
              "method": "post",
              "url": `/openform/multiFormData/selectDataByFilter?page=$page&perPage=$perPage`,
              "data": {
                "orderBy": "${orderBy}",
                "orderDir": "${orderDir}",
                "searchParams": [], //搜索参数
                "params": {}
              },
            },
            "columns": [{
              name: "${page*(perPage||10)-(perPage||10)+index+1}",
              label: "序号",
              type: 'text',
              fixed: 'left',
              align:'center',
              width:"30px"
            }],
            "headerToolbar": [
              "reload"
            ],
            "bulkActions": [],
            "footerToolbar": [
              "statistics",
              "switch-per-page",
              "pagination"
            ],

            "itemActions": [],
            "__step": 0
          }]
        }
        if (this.viewType == '1') {
          schema.body[0].api.url = schema.body[0].api.url.replace('?', '/' + basic.viewKey + '?')
        }
        //字段
        list.forEach(it => {
          this.formColumns[it.columnName.substring(0, it.columnName.indexOf('__'))].some(item => {
            if (item.columnName == it.columnName && it.showInList === '2') {
              let col = {
                name: item.columnName,
                label: item.columnTitle,
                sortable: true,
                type: 'text',
                align:'center'
              }

              const columnJson = JSON.parse(item.columnJson);

              if(columnJson.type=='input-image'){
                col.type="image"
                col.enlargeAble=true
                col.thumbMode="cover"
              }

              if(columnJson.type=='input-file'){
                col.type="input-file"
                col.disabled=true
              }

              // console.log(col.name,columnJson)
              if (columnJson.type.indexOf('input-date') > -1 && columnJson.type != 'input-date-range') {
                col.type = 'date'
                col.valueFormat = columnJson.format //值格式
                col.format = columnJson.inputFormat //显示格式
              }
              if (['select','tree-select','radios','switch'].indexOf(columnJson.type) > -1) {
                col.type = 'mapping'

                if (columnJson.source) {
                  col.source = columnJson.source
                  if(columnJson.valueField&&columnJson.labelField){
                    col.source.adaptor =
                        `let data = {};payload.forEach(item => {data[item.${columnJson.valueField}] = item.${columnJson.labelField}});return data`

                  }
                 }


                if(columnJson.type=='switch'&&(columnJson.onText||columnJson.offText)){
                  columnJson.options=[
                    {
                      value:columnJson.falseValue,
                      label:columnJson.offText,
                    },
                    {
                      value:columnJson.trueValue,
                      label:columnJson.onText,
                    }
                  ]
                }

                if (columnJson.options) {
                  col.map = {}
                  columnJson.options.forEach(item => {
                    col.map[item.value] = item.label
                  })
                }

                 if(['radios','switch'].indexOf(columnJson.type) > -1) {
                   columnJson.type='select'
                 }

                 if(columnJson.type=='tree-select') {
                   col.type = 'tree-select'
                   col.multiple=false
                     col.enableNodePath=true
                     col.hideRoot=true
                     col.showIcon= false
                     col.initiallyOpen= true
                     col.static= true
                 }
              }

              if (it.fixed) {
                col.fixed = it.fixed
              }

              if (it.searchType) {
                schema.data[item.columnName]=null
                col.searchable = {
                  "type": columnJson.type,
                  "multiple": columnJson.multiple,
                  "name": item.columnName,
                  "label": item.columnTitle,
                  "placeholder": this.searchTypeObj[it.searchType],
                  "clearable": true
                }

                if (['select'].indexOf(columnJson.type) > -1) {
                  col.searchable.searchable = true
                  col.searchable.multiple = columnJson.multiple
                  if (it.searchType == 'IN') {
                    col.searchable.multiple = true
                  }
                }

                if (columnJson.type.indexOf('input-date') > -1 && it.searchType == 'BETWEEN') {
                  //时间类型改为范围搜索
                  col.searchable.type = 'input-date-range'
                  col.searchable.text
                }


                if (columnJson.format) {
                  col.searchable.format = columnJson.format
                }
                if (columnJson.inputFormat) {
                  col.searchable.inputFormat = columnJson.inputFormat
                }

                if (col.source) {
                  col.searchable.source = col.source
                }

                if (columnJson.options) {
                  col.searchable.options = columnJson.options
                }

                schema.body[0].api.data.searchParams.push({
                  key: item.columnName,
                  value: "$" + item.columnName,
                  type: it.searchType
                })

              }
              schema.body[0].columns.push(col)
              return true
            }
          })
        })
        //全局操作
          if (action.global.indexOf('add')>-1) {
            schema.body[0].headerToolbar.push({
              "label": "新增",
              "id":"add__"+basic.viewKey,
              "type": "button",
              "actionType": "dialog",
              "level": "primary",
              "dialog": {
                "title": "新增",
                "actions": [],
                "size": "lg",
                "body": [{
                  "name": "addService",
                  "type": "service",
                  "className": "m-t",
                  // "data":{
                  //   "sysUser__user_id":''
                  // },
                  "initFetchSchema": true,
                  "schemaApi": {
                    "method": "get",
                    "url": "/openform/formDef/formDef/getJson/key/" + action.addEdit,
                    "cache": 60000
                  }
                }]
              }
            })
          }
          if(action.global.indexOf('batchDelete')>-1){
            schema.body[0].bulkActions.push(
                {
                    "id":"batchDelete__"+basic.viewKey,
                    "type": "button",
                    "level": "danger",
                    "label": "批量删除",
                    "actionType": "ajax",
                    "confirmText": "确定要批量删除？",
                    "reload": treeConfig.formKey&&treeConfig.refreshByDel?("aside_tree__"+basic.viewKey+"?tree_id=0"):"",
                    "api": {
                      "method": "post",
                      "url": "/openform/multiFormData/batchDeleteByIds/" + basic.viewKey,
                      "data":"${items|pick:"+primaryKey+"|json}",
                      "messages":{
                        "success": "删除成功",
                        "failed": "删除失败"
                      }
                    }
                }
            )
            if(schema.body[0].headerToolbar.indexOf('bulkActions')<0){
              schema.body[0].headerToolbar.push('bulkActions')
            }
          }
          if(action.global.indexOf('import')>-1){
            const btnImport = {
                 "id":"import__",
                 "type": "button",
                 "level": "success",
                 "label": "导入",

             }
            const importConfigs=action.import.map(key=>{
               return {key,name:action.importNames[key]}
            })
            btnImport.id+=JSON.stringify(importConfigs)
            schema.body[0].headerToolbar.push(btnImport)
            delete this.dataKeys.action.importNames
          }
          let exportColumns=[]
          schema.body[0].columns.forEach((item,index)=>{
            if(index&&item.name){
              exportColumns.push(item.name)
            }
          })
          if(action.global.indexOf('export')>-1){
            schema.body[0].headerToolbar.push(
                {
                    "id":"export__"+basic.viewKey,
                    "type": "export-excel",
                    "label": "导出",
                    columns:exportColumns
                }
            )
          }
          if(action.global.indexOf('exportAll')>-1){
            let api={...schema.body[0].api}
            api.url=api.url.replace('$page',1).replace('$perPage',9999999)
            schema.body[0].headerToolbar.push(
                {
                    "id":"exportAll__"+basic.viewKey,
                    "type": "export-excel",
                    "label": "全量导出",
                    api,
                    columns:exportColumns
                }
            )
          }

          //每条操作
          if (action.row.length) {
            let buttons = [],
              row = action.row;

          if (row.indexOf('detail') > -1) {
            buttons.push({
              "id":"detail__"+basic.viewKey,
              "type": "button",
              "icon": "fa fa-eye",
              "tooltip": "详情",
              "style": {
                "color": "#67C23A"
              },
              "actionType": "dialog",
              "level": "link",
              "dialog": {
                "title": "详情",
                "actions": [],
                "size": "lg",
                "body": [{
                  "name": "detailService",
                  "type": "service",
                  "className": "m-t",
                  "data":{
                    "isStatic":true
                  },
                  "initFetchSchema": true,
                  "schemaApi": {
                    "method": "get",
                    "url": "/openform/formDef/formDef/getJson/key/" + action.addEdit,
                    "cache": 60000
                  }
                }]
              }
            })
          }



            if (row.indexOf('edit') > -1) {
              buttons.push({
                "id":"edit__"+basic.viewKey,
                "tooltip": "编辑",
                "type": "button",
                "icon": "fa fa-pencil",
                "actionType": "dialog",
                "level": "link",
                "dialog": {
                  "title": "编辑",
                  "actions": [],
                  "size": "lg",
                  "body": [{
                    "name": "editService",
                    "type": "service",
                    "className": "m-t",
                    "initFetchSchema": true,
                    "schemaApi": {
                      "method": "get",
                      "url": "/openform/formDef/formDef/getJson/key/" + action.addEdit,
                      "cache": 60000,
                    }
                  }]
                }
              })
            }

          if (row.indexOf('delete') > -1) {
            buttons.push({
              "id":"delete__"+basic.viewKey,
              "type": "button",
              "tooltip": "删除",
              "icon": "fa fa-times text-danger",
              "actionType": "ajax",
              "level": "link",
              "style": {
                "color": "red"
              },
              "reload": treeConfig.formKey&&treeConfig.refreshByDel?("aside_tree__"+basic.viewKey+"?tree_id=0"):"",
              "className": "text-danger",
              "confirmText": "确定要删除？",
              "api": {
                "method": "post",
                "url": "/openform/multiFormData/batchDeleteByIds/" + basic.viewKey,
                "data":["${"+primaryKey+"}"],
                "messages":{
                  "success": "删除成功",
                  "failed": "删除失败"
                }
              }
            })
          }
          if (row.indexOf('select') > -1) {
            buttons.push({
              "type": "button",
              "tooltip": "选择",
              "icon": "fa fa-check",
              "level": "link",
              "onEvent": {
                "click": {
                  "actions": [
                    {
                      "actionType": "broadcast",
                      "args": {
                        "eventName":this.formKey + "_data"
                      },
                      "data": {
                        "&": "$$"
                      },
                    },
                    {
                      "actionType": "closeDialog"
                    }
                  ]
                }
              }
            })
          }
          schema.body[0].columns.push({
            "type": "operation",
            "label": "操作",
            "fixed": "right",
            align:'center',
            "width":buttons.length*23,
            buttons
          })
        }

        //列表模式开启了边栏树
        if (treeConfig.formKey) {
          schema.regions.push("aside")
          schema.body[0].api.data.params.tree_id="${crud__"+basic.viewKey+"_tree_id}"
          schema.body[0].api.sendOn="this.crud__"+basic.viewKey+"_tree_id"
          schema.aside=[
            {
              "type": "service",
              "name": "aside_tree__"+basic.viewKey,
              "className": "m-t",
              "api": {
                "url": "openform/multiFormData/selectTreeDataByViewKeyAndParams/"+basic.viewKey,
                "method": "post",
                "responseData": {
                  "tree_options": "${items|pick}",
                  "tree_id":"${items[0].value}"
                }
              },
              "body":[
                  {
                    "type": "form",
                    "body": [
                      {
                        "type": "input-text",
                        "label": "tree_id",
                        "name": "tree_id",
                        "style":{
                          "display":"none"
                        }
                      }
                    ],
                    "target": "page__"+basic.viewKey+"?crud__"+basic.viewKey+"_tree_id=${tree_id}",
                    "submitOnChange": true,
                    "submitOnInit": true,
                    "wrapWithPanel": false,
                    "visibleOn":"${tree_id&&!crud__"+basic.viewKey+"_tree_id}"
                },
                {
                    "type": "form",
                    "body": [
                      {
                        "type": "input-tree",
                        "name": "crud__"+basic.viewKey+"_tree_id",
                        "inputClassName": "no-border",
                        "submitOnChange": true,
                        "source": "${tree_options}",
                        "multiple": false,
                        "enableNodePath": false,
                        "hideRoot": true,
                        "showIcon": false,
                        "initiallyOpen": true,
                        "searchable": true
                      }
                    ],
                    "target": "page__"+basic.viewKey+"?crud__"+basic.viewKey+"_tree_id=${crud__"+basic.viewKey+"_tree_id},crud__"+basic.viewKey,
                    "submitOnChange": true,
                    "submitOnInit": true,
                    "wrapWithPanel": false,
                    "visibleOn":"${crud__"+basic.viewKey+"_tree_id&&tree_id&&tree_id!=0}"
                }
              ]
            }
          ]
          schema.asideMinWidth=240
          schema.asideMaxWidth=500
          schema.asideResizor=true
        }
        this.previewOrSave(schema,columnAuths)
      },
      setFormSchema(columnAuths) {
        const {action}=this.dataKeys
        let schema = {
          "type": "page",
          "style": {
            "boxShadow": " 0px 0px 0px 0px transparent"
          },
          "pullRefresh": {
            "disabled": true
          },
          "regions": [
            "body"
          ],
          "body": [{
            "name": "editService",
            "type": "service",
            // "api": {
            //   "method": "post",
            //   "url": `/openform/multiFormData/selectDataByFilter`,
            //   "data": {
            //     "params": {}
            //   }
            // },
            "className": "m-t",
            "initFetchSchema": true,
            "schemaApi": {
              "method": "get",
              "url": "/openform/formDef/formDef/getJson/key/" + action.addEdit,
              "cache": 60000
            }
          }]
        }
        this.previewOrSave(schema, columnAuths)
      },
      previewOrSave(schema, columnAuths) {
        const {basic}=this.dataKeys

        let param = {
          id: this.id,
          schemaJson: JSON.stringify(schema),
          json: JSON.stringify(this.dataKeys),
          formColumnAuths: columnAuths,
          ...basic
        }
        // console.log(JSON.stringify(schema),'-----------')
        this.saveOrUpdate(param);
      },
      saveOrUpdate(param){
        this.loading = true
        saveOrUpdate(param).then(res => {
          if (res.code == 200) {
            if (this.isPreview) {
              this.businessId=param.viewKey
              this.previewVisible = true
            }else{
              this.$message.success('保存成功')
              this.dialogFormVisible = false
            }

            if(this.autoSave){
              this.$emit('autoSave')
            }else{
              this.$emit('getGroups')
              this.$emit('getList')
            }
          }
        }).finally(() => {
          this.loading = false
        })
      },
    }
  };
</script>
<style lang="scss">
  // ::v-deep .el-dialog__wrapper{
  //   z-index:1000 !important;
  // }
</style>
